<?php

namespace app\common\controller;
use app\index\model\Admin;
use think\Controller;
use think\Request;
use think\Session;

class Base extends Controller
{

    protected  $allowAccess = [
        'index/login/login',
        'index/login/logout',
        ];
    protected $allowUser = 'admin';
    protected $url = '';
    public function __construct(Request $request = null)
    {
        parent::__construct($request);

        # 权限的判断
        $this->getUrl($request);

        #获取用户名字
        $name = Session::get('admin_info')['admin_name'];

        # 过滤掉允许的请求
        if(!in_array($this->url,$this->allowAccess) && $name != $this->allowUser){
            $this->check();
        }


    }


    # 获取当前访问的url
    private function getUrl($request){
        $module = $request->module();
        $controller = strtolower($request->controller());
        $action = $request->action();
        $this->url = $module.'/'.$controller.'/'.$action;
    }


    # 判断权限的方法
    private function check(){
        # 首先获取用户的id
        $id = Session::get('admin_info')['admin_id'];

        # 通过id去获取对应用户的权限
        $admin = new Admin();
        $res = $admin->alias('ad')
                    ->field('a.access_url')
                    ->where(['ad.admin_id' => $id])
                    ->join('admin_role ar','ad.admin_id=ar.ar_admin_id')
                    ->join('role r','ar.ar_role_id=r.role_id')
                    ->join('role_access ra','r.role_id=ra.ra_role_id')
                    ->join('access a','ra.ra_access_id=a.access_id')
                    ->select();

        $access_url = [];
        foreach ($res as $v){
            $access_url[] = strtolower($v->access_url);
        }

        if(!in_array($this->url,$access_url)){
            # 说明没有权限访问
            die('没有权限访问');
        }



    }

}